<?php

namespace app\common\service;

use Firebase\JWT\JWT;
use think\Exception;
use think\Model;

class TokenService
{
    const key = "0j94ubk5Krarup2hL1pr5Hr7FhGkU5Vi";
    const expire = 60 * 60 * 24 * 30;

    public static function generateJwt($id)
    {
        $token = array(
            "id" => $id,
            "exp" => time() + self::expire
        );

        return JWT::encode($token, self::key);
    }

    /**
     * @param Model $model
     * @return Model
     * @throws Exception
     */
    public static function auth(Model $model)
    {
        $jwt = request()->header('Authorization');
        if (empty($jwt)) {
            throw new Exception('token无效');
        }
        try {
            $payload = JWT::decode($jwt, self::key, ['HS256']);
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        return $model->where('id', $payload->id)->findOrFail();
    }

}